using System;
using System.Collections;
using System.Collections.Generic;
using Cinemachine;
using UnityEngine;
using Random = UnityEngine.Random;

public class CameraController : MonoBehaviour
{
    public static CameraController instance;
    private bool isShake = false;
    public GameObject player;
    private Vector3 fellowOffset;   //相机与player的初始偏移

    private void Awake()
    {
        instance = this;
    }

    private void Start()
    {
        fellowOffset = transform.position - player.transform.position;
    }

    private void Update()
    {
        transform.position = player.transform.position + fellowOffset;  //让相机始终跟着player
    }

    public void StartShake(float duration, float strength)
    {
        if (!isShake)
        {
            StartCoroutine(Shake(duration, strength));
        }
    }

    //1.为什么需要加协程才能启用震动，2.为什么直接用transform.positon震的是player
    //1、不添加协程，函数会在一帧内执行完毕，不管函数里有没有循环
    //2、因为是在playerController脚本中调用该函数，相当于在该脚本中写入那段代码，所以transform.positon指的是player的位置
    IEnumerator Shake(float duration, float strength)
    {
        isShake = true;
        Transform camera = Camera.main.transform;
        Vector3 startPos = camera.position;
        while (duration>0)
        {
            camera.position = Random.insideUnitSphere * strength + startPos;
            duration -= Time.deltaTime;
            yield return null;
        }

        camera.position = startPos;
        isShake = false;
    }

    public void StartPause(float duration,float timeScale)
    {
        StartCoroutine(Pause(duration, timeScale));
    }

    IEnumerator Pause(float duration, float timeScale)
    {
        float puaseFrame = duration / 60;
        Time.timeScale = timeScale;
        yield return new WaitForSecondsRealtime(puaseFrame);
        Time.timeScale = 1;
    }
}
